﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>物料产品管理</title>
    <link rel="stylesheet" href="../../scripts/layui-v2.5.6/layui/css/layui.css">
    <script src="../../scripts/jquery-3.4.1.min.js"></script>
    <script src="../../scripts/layui-v2.5.6/layui/layui.js"></script>
</head>
<body>
<style>
    .container {
        display: flex;
        padding: 15px;
        background-color: #f2f2f2;
    }
    .left-tree {
        width: 250px;
        background-color: #fff;
        padding: 15px;
        margin-right: 15px;
        border-radius: 2px;
    }
    .right-content {
        flex: 1;
        background-color: #fff;
        padding: 15px;
        border-radius: 2px;
    }
    .form-item {
        margin-bottom: 20px;
    }
    .form-label {
        width: 100px;
        line-height: 38px;
        padding-right: 10px;
        color: #333;
    }
    .form-label.required::before {
        content: "*";
        color: #FF5722;
        margin-right: 2px;
    }
    .form-input-error {
        color: #FF5722;
        font-size: 12px;
        margin-top: 5px;
        display: none;
    }
    .upload-box {
        width: 150px;
        height: 150px;
        border: 1px dashed #ddd;
        text-align: center;
        cursor: pointer;
        position: relative;
    }
    .upload-box i {
        font-size: 32px;
        color: #999;
        margin-top: 50px;
    }
    .upload-tip {
        color: #999;
        font-size: 12px;
        margin-top: 10px;
    }
</style>

<div class="container">
    <!-- 左侧树形图 -->
    <div class="left-tree">
        <ul id="materialTree"></ul>
    </div>

    <!-- 右侧内容区 -->
    <div class="right-content">
        <!-- 搜索栏 -->
        <div class="layui-form" lay-filter="searchForm">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <input type="text" name="materialCode" placeholder="请输入物料编码" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-inline">
                    <input type="text" name="materialName" placeholder="请输入物料名称" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-inline">
                    <button type="button" class="layui-btn" id="searchBtn"><i class="layui-icon layui-icon-search"></i> 搜索</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </div>

        <!-- 按钮组 -->
        <div class="layui-btn-group" style="margin-bottom: 10px;">
            <button class="layui-btn" id="addBtn"><i class="layui-icon layui-icon-add-1"></i> 新增</button>
            <button class="layui-btn layui-btn-warm" id="editBtn"><i class="layui-icon layui-icon-edit"></i> 修改</button>
            <button class="layui-btn layui-btn-danger" id="deleteBtn"><i class="layui-icon layui-icon-delete"></i> 删除</button>
        </div>

        <!-- 数据表格 -->
        <table id="materialTable" lay-filter="materialTable"></table>
    </div>
</div>

<!-- 添加/编辑表单 -->
<div class="layui-form" lay-filter="materialForm" id="materialForm" style="display: none; padding: 20px;">
    <div class="layui-form-item">
        <label class="layui-form-label required">物料编码</label>
        <div class="layui-input-block">
            <div class="layui-input-inline" style="width: calc(100% - 90px);">
                <input type="text" name="materialCode" required lay-verify="required" placeholder="请输入物料编码" class="layui-input">
            </div>
            <div class="layui-input-inline" style="width: 80px;">
                <input type="checkbox" name="autoGenerate" lay-skin="switch" lay-text="自动|手动" lay-filter="autoGenerate">
            </div>
            <div class="form-input-error"></div>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label required">物料名称</label>
        <div class="layui-input-block">
            <input type="text" name="materialName" required lay-verify="required" placeholder="请输入物料名称" class="layui-input">
            <div class="form-input-error"></div>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label required">物料分类</label>
        <div class="layui-input-block">
            <input type="text" name="categoryName" readonly class="layui-input" placeholder="请选择物料分类" id="treeSelectorInput">
            <input type="hidden" name="categoryId" lay-verify="required">
            <div id="treeSelectContent" style="display:none; position: absolute; z-index: 999; background-color: #fff; width: 100%; border: 1px solid #e6e6e6; border-radius: 2px; padding: 5px 0;">
                <div id="categoryTree"></div>
            </div>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">规格型号</label>
        <div class="layui-input-block">
            <textarea name="specModel" placeholder="请输入规格型号" class="layui-textarea"></textarea>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label required">单位</label>
        <div class="layui-input-block">
            <select name="unit" lay-verify="required">
                <option value="">请选择单位</option>
                <option value="个">个</option>
                <option value="件">件</option>
                <option value="套">套</option>
                <option value="箱">箱</option>
                <option value="kg">kg</option>
                <option value="吨">吨</option>
                <option value="米">米</option>
            </select>
            <div class="form-input-error"></div>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">是否启用</label>
        <div class="layui-input-block">
            <input type="radio" name="isEnabled" value="true" title="是" checked>
            <input type="radio" name="isEnabled" value="false" title="否">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">安全库存</label>
        <div class="layui-input-block">
            <input type="radio" name="safetyStock" value="true" title="是">
            <input type="radio" name="safetyStock" value="false" title="否" checked>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">物料图片</label>
        <div class="layui-input-block">
            <div class="upload-box" id="uploadImage">
                <i class="layui-icon layui-icon-add-1"></i>
                <div class="layui-hide" id="uploadPreview">
                    <img src="" style="max-width: 100%; max-height: 100%;">
                </div>
            </div>
            <div class="upload-tip">请上传不大于5MB的jpg/png/jpeg格式图片</div>
        </div>
    </div>



    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="saveBtn">保存</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</div>

<!-- 修改物料弹出框 -->
<div id="editMaterialForm" style="display: none; padding: 20px;">
    <form class="layui-form" lay-filter="editForm">
        <div class="layui-form-item">
            <label class="layui-form-label">物料编码</label>
            <div class="layui-input-block">
                <input type="text" name="materialCode" class="layui-input" required lay-verify="required" placeholder="请输入物料编码">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">物料名称</label>
            <div class="layui-input-block">
                <input type="text" name="materialName" class="layui-input" required lay-verify="required" placeholder="请输入物料名称">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">规格型号</label>
            <div class="layui-input-block">
                <input type="text" name="specModel" class="layui-input" placeholder="请输入规格型号">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">单位</label>
            <div class="layui-input-block">
                <select name="unit" lay-verify="required">
                    <option value="">请选择单位</option>
                    <option value="个">个</option>
                    <option value="件">件</option>
                    <option value="套">套</option>
                    <option value="箱">箱</option>
                    <option value="kg">kg</option>
                    <option value="吨">吨</option>
                    <option value="米">米</option>
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">物料/产品分类</label>
            <div class="layui-input-block">
                <input type="text" name="categoryName" class="layui-input" placeholder="请选择物料分类" id="editTreeSelectorInput" readonly style="cursor: pointer;" required lay-verify="required">
                <input type="hidden" name="categoryId" lay-verify="required">
                <div id="editTreeSelectContent" style="display:none; position: absolute; z-index: 999; background-color: #fff; width: 100%; border: 1px solid #e6e6e6; border-radius: 2px; padding: 5px 0;">
                    <div id="editCategoryTree"></div>
                </div>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">是否启用</label>
            <div class="layui-input-block">
                <input type="radio" name="isEnabled" value="true" title="是">
                <input type="radio" name="isEnabled" value="false" title="否">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">安全库存</label>
            <div class="layui-input-block">
                <input type="radio" name="safetyStock" value="true" title="是">
                <input type="radio" name="safetyStock" value="false" title="否">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">物料图片</label>
            <div class="layui-input-block">
                <div class="upload-box" id="editUploadImage">
                    <i class="layui-icon layui-icon-add-1"></i>
                    <div class="layui-hide" id="editUploadPreview">
                        <img src="" style="max-width: 100%; max-height: 100%;">
                    </div>
                </div>
                <div class="upload-tip">请上传不大于5MB的jpg/png/jpeg格式图片</div>
            </div>
        </div>



    </form>

    <!-- BOM组成 -->
    <div class="layui-form-item">
        <div class="layui-card">
            <div class="layui-card-header" style="display: flex; justify-content: space-between; align-items: center;">
                <span>BOM组成</span>
                <div>
                    <button class="layui-btn layui-btn-primary layui-btn-sm" id="editAddBomBtn">+ 新增</button>
                    <button class="layui-btn layui-btn-primary layui-btn-sm" id="editDeleteBomBtn">删除</button>
                </div>
            </div>
            <div class="layui-card-body">
                <table class="layui-table" lay-skin="line">
                    <thead>
                        <tr>
                            <th style="width: 40px;"><input type="checkbox" lay-skin="primary" lay-filter="bomCheckAll"></th>
                            <th>物料编码</th>
                            <th>物料名称</th>
                            <th>规格</th>
                            <th>单位</th>
                            <th>使用比例</th>
                            <th>备注</th>
                            <th style="width: 100px;">操作</th>
                        </tr>
                    </thead>
                    <tbody id="bomTableBody">
                        <tr>
                            <td><input type="checkbox" lay-skin="primary"></td>
                            <td>YCL00070</td>
                            <td>鸡蛋</td>
                            <td>个</td>
                            <td>PCS</td>
                            <td>0.7</td>
                            <td></td>
                            <td>
                                <a class="layui-btn layui-btn-xs layui-btn-primary" lay-event="editBom">修改</a>
                                <a class="layui-btn layui-btn-xs layui-btn-primary" lay-event="deleteBom">删除</a>
                            </td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" lay-skin="primary"></td>
                            <td>YCL00069</td>
                            <td>西红柿</td>
                            <td>红色</td>
                            <td>g</td>
                            <td>0.3</td>
                            <td></td>
                            <td>
                                <a class="layui-btn layui-btn-xs layui-btn-primary" lay-event="editBom">修改</a>
                                <a class="layui-btn layui-btn-xs layui-btn-primary" lay-event="deleteBom">删除</a>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <div style="display: flex; justify-content: space-between; align-items: center; padding: 10px 0;">
                    <span id="bomTotalCount">共 2 条</span>
                    <div class="layui-btn-group">
                        <button type="button" class="layui-btn layui-btn-primary layui-btn-sm">
                            <i class="layui-icon">&#xe603;</i>
                        </button>
                        <button type="button" class="layui-btn layui-btn-primary layui-btn-sm layui-bg-blue" style="color: white;">1</button>
                        <button type="button" class="layui-btn layui-btn-primary layui-btn-sm">
                            <i class="layui-icon">&#xe602;</i>
                        </button>
                        <div class="layui-inline" style="margin-left: 10px;">
                            <select class="layui-input-inline" style="height: 30px; width: 80px;">
                                <option>10条/页</option>
                            </select>
                        </div>
                        <div class="layui-inline" style="margin-left: 10px;">
                            前往 <input type="text" class="layui-input layui-input-inline" style="height: 30px; width: 50px;" value="1"> 页
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 底部按钮 -->
    <div class="layui-form-item" style="margin-top: 20px; text-align: center;">
        <button class="layui-btn" lay-submit lay-filter="editSubmit">确定</button>
        <button type="button" class="layui-btn layui-btn-primary" onclick="layer.closeAll()">关闭</button>
    </div>
</div>

<!-- BOM组成表格 -->
<div id="bomTable" style="display: none; padding: 20px;">
    <div class="layui-btn-group" style="margin-bottom: 10px;">
        <button class="layui-btn layui-btn-sm" id="addBomBtn">新增</button>
        <button class="layui-btn layui-btn-danger layui-btn-sm" id="deleteBomBtn">删除</button>
    </div>
    <table class="layui-table" id="bomDetailTable" lay-filter="bomDetailTable">
        <thead>
            <tr>
                <th><input type="checkbox" lay-skin="primary" lay-filter="bomCheckAll"></th>
                <th>物料编码</th>
                <th>物料名称</th>
                <th>规格</th>
                <th>单位</th>
                <th>使用比例</th>
                <th>备注</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <!-- 数据将通过JavaScript动态添加 -->
        </tbody>
    </table>
</div>

<!-- 表格操作列模板 -->
<script type="text/html" id="tableBar">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<!-- BOM物料选择弹窗 -->
<div id="bomMaterialSelectDialog" style="display: none; padding: 20px;">
    <div class="container" style="padding: 0;">
        <!-- 左侧树形图 -->
        <div class="left-tree">
            <ul id="bomMaterialTree" lay-filter="bomMaterialTree"></ul>
        </div>

        <!-- 右侧内容区 -->
        <div class="right-content">
            <!-- 搜索栏 -->
            <div class="search-box">
                <div class="layui-form" lay-filter="bomSearchForm">
                    <div class="layui-inline">
                        <input type="text" name="materialCode" placeholder="请输入物料编码" autocomplete="off" class="layui-input">
                    </div>
                    <div class="layui-inline">
                        <input type="text" name="materialName" placeholder="请输入物料名称" autocomplete="off" class="layui-input">
                    </div>
                    <div class="layui-inline">
                        <button type="button" class="layui-btn" id="bomSearchBtn">
                            <i class="layui-icon layui-icon-search"></i> 搜索
                        </button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </div>

            <!-- 数据表格 -->
            <table id="bomMaterialTable" lay-filter="bomMaterialTable"></table>
        </div>
    </div>

    <!-- 底部按钮 -->
    <div class="layui-form-item" style="margin-top: 20px; text-align: center;">
        <button class="layui-btn" id="confirmBomSelectBtn">确定</button>
        <button type="button" class="layui-btn layui-btn-primary" onclick="layer.closeAll()">取消</button>
    </div>
</div>

<script>
layui.use(['form', 'table', 'tree', 'layer', 'upload'], function(){
    var form = layui.form;
    var table = layui.table;
    var tree = layui.tree;
    var layer = layui.layer;
    var upload = layui.upload;
    var $ = layui.$;

    // 加载分类树和初始化表格
    function loadCategoryData() {
        $.ajax({
            url: '/MaterialType/GetTreeAsyncgrx',
            type: 'GET',
            dataType: 'json',
            success: function(res) {
                console.log('获取到的树形数据:', res);
                if(res && res.length > 0) {
                    // 直接使用后端返回的数据渲染树
                    tree.render({
                        elem: '#materialTree',
                        data: [{
                            title: '物料分类',
                            id: 0,
                            spread: true,
                            children: res
                        }],
                        click: function(obj){
                            if(obj.data.id > 0) { // 不是根节点才触发查询
                                table.reload('materialTable', {
                                    where: {
                                        categoryId: obj.data.id
                                    },
                                    page: { curr: 1 }
                                });
                            }
                        }
                    });
                }
            },
            error: function(xhr, status, error) {
                console.error('加载分类数据失败:', error);
                layer.msg('加载分类数据失败', {icon: 2});
            }
        });
    }

    // 初始化表格
    table.render({
        elem: '#materialTable',
        url: '/Materialproductmanagement/GetMaterialproductModel',
        method: 'get',
        request: {
            pageName: 'page',
            limitName: 'limit'
        },
        where: {
            code: '',
            name: ''
        },
        page: {
            curr: 1,
            limit: 10
        },
        toolbar: true,
        defaultToolbar: ['filter', 'exports', 'print'],
        parseData: function(res) {
            return {
                "code": 200,
                "msg": "",
                "count": res.pageCount,
                "data": res.listDate || []
            };
        },
        cols: [[
            {type: 'checkbox'},
            {field: 'materielCode', title: '物料编码', width: 120},
            {field: 'materielName', title: '物料名称', width: 200},
            {field: 'materielUrl', title: '物料图片', width: 100, templet: function(d){
                return d.materielUrl ? '<img src="'+ d.materielUrl +'" style="max-width:50px;">' : '';
            }},
            {field: 'specifications', title: '规格型号', width: 120},
            {field: 'unitsId', title: '单位', width: 80},
            {field: 'materielTypeId', title: '所属分类', width: 150},
            {field: 'isNo', title: '是否启用', width: 100, templet: function(d){
                return d.isNo === 1 ? '<span class="layui-badge layui-bg-green">是</span>' : '<span class="layui-badge layui-bg-gray">否</span>';
            }},
            {field: 'isSecure', title: '安全库存', width: 100, templet: function(d){
                return d.isSecure === 1 ? '<span class="layui-badge layui-bg-green">是</span>' : '<span class="layui-badge layui-bg-gray">否</span>';
            }},
            {field: 'createTime', title: '创建时间', width: 160},
            {title: '操作', toolbar: '#tableBar', width: 120, fixed: 'right'}
        ]],
        limits: [5, 10, 15, 20],
        limit: 10,
        response: {
            statusCode: 200 // 成功的状态码
        },
        text: {
            none: '暂无相关数据'
        }
    });

    // 初始化编辑表单的上传组件
    upload.render({
        elem: '#editUploadImage',
        url: '/Materialproductmanagement/loadUrl',
        accept: 'images',
        acceptMime: 'image/jpg,image/jpeg,image/png',
        size: 5120,
        done: function(res){
            if(res.code === 0){
                $('#editUploadPreview').removeClass('layui-hide').find('img').attr('src', res.data.src);
                $('#editUploadImage i').hide();
                layer.msg('上传成功');
            } else {
                layer.msg(res.msg || '上传失败');
            }
        }
    });

    // 初始化新增表单的上传组件
    upload.render({
        elem: '#uploadImage',
        url: '/Materialproductmanagement/loadUrl',
        accept: 'images',
        acceptMime: 'image/jpg,image/jpeg,image/png',
        size: 5120,
        done: function(res){
            if(res.code === 0){
                $('#uploadPreview').removeClass('layui-hide').find('img').attr('src', res.data.src);
                $('#uploadImage i').hide();
                layer.msg('上传成功');
            } else {
                layer.msg(res.msg || '上传失败');
            }
        }
    });

    // 自动生成编码开关事件
    form.on('switch(autoGenerate)', function(data){
        var $input = $('input[name="materialCode"]');
        if(data.elem.checked){
            var loading = layer.load(1);
            $.ajax({
                url: '/Materialproductmanagement/GenerateMaterialCode',
                type: 'GET',
                success: function(res){
                    layer.close(loading);
                    if(res){
                        $input.val(res).attr('disabled', 'disabled');
                        $input.removeAttr('lay-verify').removeAttr('lay-reqText');
                        layer.msg('编码生成成功');
                    } else {
                        layer.msg('生成编码失败');
                        $(data.elem).prop('checked', false);
                        form.render('checkbox');
                    }
                },
                error: function(){
                    layer.close(loading);
                    layer.msg('服务器错误');
                    $(data.elem).prop('checked', false);
                    form.render('checkbox');
                }
            });
        } else {
            $input.val('').removeAttr('disabled');
            $input.attr('lay-verify', 'required');
            layer.msg('已切换到手动输入模式');
        }
    });

    // 搜索按钮点击事件
    $('#searchBtn').on('click', function(){
        var loading = layer.load(1);
        table.reload('materialTable', {
            where: {
                code: $('input[name="materialCode"]').val(),
                name: $('input[name="materialName"]').val()
            },
            page: {
                curr: 1 // 重新从第一页开始
            },
            done: function() {
                layer.close(loading);
            }
        });
    });

    // 初始化分类选择树（新增表单）
    function initCategorySelector() {
        $.ajax({
            url: '/MaterialType/GetTreeAsyncgrx',
            type: 'GET',
            dataType: 'json',
            success: function(res) {
                if(res && res.length > 0) {
                    // 渲染选择树
                    tree.render({
                        elem: '#categoryTree',
                        data: res,
                        onlyIconControl: true,
                        click: function(obj){
                            var data = obj.data;
                            $('#treeSelectorInput').val(data.title);
                            $('input[name="categoryId"]').val(data.id);
                            $('#treeSelectContent').hide();
                            form.render();
                        }
                    });
                }
            },
            error: function(xhr, status, error) {
                console.error('加载分类数据失败:', error);
                layer.msg('加载分类数据失败', {icon: 2});
            }
        });
    }

    // 初始化编辑表单分类选择树
    function initEditCategorySelector() {
        $.ajax({
            url: '/MaterialType/GetTreeAsyncgrx',
            type: 'GET',
            dataType: 'json',
            success: function(res) {
                if(res && res.length > 0) {
                    // 渲染编辑表单的选择树
                    tree.render({
                        elem: '#editCategoryTree',
                        data: res,
                        onlyIconControl: true,
                        click: function(obj){
                            var data = obj.data;
                            $('#editTreeSelectorInput').val(data.title);
                            $('input[name="categoryId"]', '#editMaterialForm').val(data.id);
                            $('#editTreeSelectContent').hide();
                            form.render();
                        }
                    });
                }
            },
            error: function(xhr, status, error) {
                console.error('加载分类数据失败:', error);
                layer.msg('加载分类数据失败', {icon: 2});
            }
        });
    }

    // 点击输入框显示树形选择（新增表单）
    $('#treeSelectorInput').on('click', function(e){
        e.stopPropagation();
        $('#treeSelectContent').toggle();
    });

    // 点击输入框显示树形选择（编辑表单）
    $('#editTreeSelectorInput').on('click', function(e){
        e.stopPropagation();
        $('#editTreeSelectContent').toggle();
    });

    // 点击其他地方关闭树形选择
    $(document).on('click', function(){
        $('#treeSelectContent').hide();
        $('#editTreeSelectContent').hide();
    });

    // 阻止树形选择的点击事件冒泡
    $('#treeSelectContent').on('click', function(e){
        e.stopPropagation();
    });

    // 阻止编辑表单树形选择的点击事件冒泡
    $('#editTreeSelectContent').on('click', function(e){
        e.stopPropagation();
    });

    // 添加按钮点击事件
    $('#addBtn').on('click', function(){
        layer.open({
            type: 1,
            title: '添加物料',
            area: ['700px', '90%'],
            content: $('#materialForm'),
            success: function(){
                // 重置表单
                form.val('materialForm', {
                    materialCode: '',
                    materialName: '',
                    categoryName: '',
                    categoryId: '',
                    specModel: '',
                    unit: '',
                    isEnabled: 'true',
                    safetyStock: 'false',
                    autoGenerate: false
                });
                $('input[name="materialCode"]').removeAttr('disabled');
                $('#uploadPreview').addClass('layui-hide');
                $('#uploadImage i').show();
                $('.form-input-error').hide();
                
                // 初始化分类选择器
                initCategorySelector();
            }
        });
    });

    // 编辑表单提交事件
    form.on('submit(editSubmit)', function(data){
        console.log('提交表单数据:', data.field);
        console.log('完整的data对象:', data);
        
        var categoryId = $('input[name="categoryId"]', '#editMaterialForm').val();
        console.log('选择的分类ID:', categoryId);
        
        if(!categoryId) {
            layer.msg('请选择物料分类');
            return false;
        }

        // 检查是否有编辑中的物料ID
        if(!window.editingMaterialId) {
            layer.msg('无法获取要修改的物料ID');
            return false;
        }

        // 直接从表单元素获取值进行验证，而不是依赖data.field
        var materialCode = $('input[name="materialCode"]', '#editMaterialForm').val();
        var materialName = $('input[name="materialName"]', '#editMaterialForm').val();
        var unit = $('select[name="unit"]', '#editMaterialForm').val();
        var specModel = $('input[name="specModel"]', '#editMaterialForm').val();
        
        console.log('直接获取的字段值:', {
            materialCode: materialCode,
            materialName: materialName,
            unit: unit,
            specModel: specModel
        });

        // 表单验证
        if(!materialCode || materialCode.trim() === '') {
            layer.msg('请输入物料编码');
            return false;
        }

        if(!materialName || materialName.trim() === '') {
            layer.msg('请输入物料名称');
            return false;
        }

        if(!unit || unit.trim() === '') {
            layer.msg('请选择单位');
            return false;
        }

        // 获取上传的图片URL
        var imageUrl = $('#editUploadPreview img').attr('src');
        
        // 获取单选框的值
        var isEnabled = $('input[name="isEnabled"]:checked', '#editMaterialForm').val();
        var safetyStock = $('input[name="safetyStock"]:checked', '#editMaterialForm').val();
        
        console.log('单选框值:', {
            isEnabled: isEnabled,
            safetyStock: safetyStock
        });
        
        // 构造DTO对象
        var dto = {
            Id: window.editingMaterialId, // 使用存储的ID
            MaterielCode: materialCode,
            MaterielName: materialName,
            MaterielTypeId: parseInt(categoryId),
            MaterielTypePid: 0,
            Specifications: specModel || '',
            UnitsId: unit,
            IsNo: isEnabled === 'true' ? 1 : 0,
            IsSecure: safetyStock === 'true' ? 1 : 0,
            MaterielUrl: imageUrl || '',
            CreateTime: new Date().toISOString()
        };

        console.log('准备提交的DTO:', dto);

        var loading = layer.load();
        $.ajax({
            url: '/Materialproductmanagement/UpdateMaterialproductmanagement',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(dto),
            success: function(res){
                layer.close(loading);
                console.log('服务器响应:', res);
                if(res.code === 0){
                    layer.closeAll('page');
                    layer.msg('修改成功');
                    table.reload('materialTable');
                } else {
                    layer.msg(res.msg || '修改失败');
                }
            },
            error: function(xhr, status, error){
                layer.close(loading);
                console.error('AJAX错误:', {
                    status: xhr.status,
                    statusText: xhr.statusText,
                    responseText: xhr.responseText,
                    error: error
                });
                
                var errorMsg = '修改失败';
                if(xhr.responseText) {
                    try {
                        var errorObj = JSON.parse(xhr.responseText);
                        errorMsg = errorObj.msg || errorObj.message || '服务器错误';
                    } catch(e) {
                        errorMsg = '服务器错误: ' + xhr.status;
                    }
                }
                layer.msg(errorMsg);
            }
        });
        return false;
    });

    // 新增表单提交事件
    form.on('submit(saveBtn)', function(data){
        if(!data.field.categoryId) {
            layer.msg('请选择物料分类');
            return false;
        }

        // 获取上传的图片URL
        var imageUrl = $('#uploadPreview img').attr('src');
        
        // 构造DTO对象
        var dto = {
            MaterielCode: data.field.materialCode,
            MaterielName: data.field.materialName,
            MaterielTypeId: parseInt(data.field.categoryId),
            MaterielTypePid: 0, // 默认值
            Specifications: data.field.specModel || '',
            UnitsId: data.field.unit,
            IsNo: data.field.isEnabled === 'true' ? 1 : 0,
            IsSecure: data.field.safetyStock === 'true' ? 1 : 0,
            MaterielUrl: imageUrl || '',
            CreateTime: new Date().toISOString()
        };

        console.log('提交的数据:', dto); // 调试用

        var loading = layer.load();
        $.ajax({
            url: '/Materialproductmanagement/AddMaterialproductmanagement',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(dto),
            success: function(res){
                layer.close(loading);
                if(res.code === 0){
                    layer.closeAll('page');
                    layer.msg(res.msg || '保存成功');
                    table.reload('materialTable');
                } else {
                    layer.msg(res.msg || '保存失败');
                }
            },
            error: function(xhr, status, error){
                layer.close(loading);
                console.error('保存失败:', xhr.responseText);
                layer.msg('服务器错误: ' + (xhr.responseText || error));
            }
        });
        return false;
    });

    // 表格工具条事件
    table.on('tool(materialTable)', function(obj){
        var data = obj.data;
        if(obj.event === 'edit'){
            // 调用后端API获取详细数据
            var loading = layer.load(1);
            $.ajax({
                url: '/Materialproductmanagement/GetMaterialproductById',
                type: 'GET',
                data: { id: data.id },
                success: function(res){
                    layer.close(loading);
                    if(res.code === 0){
                        var detailData = res.data;
                        
                        // 打开修改弹窗
                        layer.open({
                            type: 1,
                            title: '修改物料/产品',
                            area: ['800px', '90%'],
                            content: $('#editMaterialForm'),
                            success: function(){
                                // 设置隐藏的ID字段
                                window.editingMaterialId = detailData.id;
                                
                                // 直接设置表单字段值
                                $('input[name="materialCode"]', '#editMaterialForm').val(detailData.materielCode);
                                $('input[name="materialName"]', '#editMaterialForm').val(detailData.materielName);
                                $('input[name="specModel"]', '#editMaterialForm').val(detailData.specifications);
                                $('select[name="unit"]', '#editMaterialForm').val(detailData.unitsId);
                                
                                // 设置单选框
                                $('input[name="isEnabled"][value="' + (detailData.isNo === 1 ? 'true' : 'false') + '"]', '#editMaterialForm').prop('checked', true);
                                $('input[name="safetyStock"][value="' + (detailData.isSecure === 1 ? 'true' : 'false') + '"]', '#editMaterialForm').prop('checked', true);

                                // 设置物料分类ID
                                $('input[name="categoryId"]', '#editMaterialForm').val(detailData.materielTypeId);
                                
                                console.log('设置完成后的表单值验证:', {
                                    materialCode: $('input[name="materialCode"]', '#editMaterialForm').val(),
                                    materialName: $('input[name="materialName"]', '#editMaterialForm').val(),
                                    specModel: $('input[name="specModel"]', '#editMaterialForm').val(),
                                    unit: $('select[name="unit"]', '#editMaterialForm').val(),
                                    categoryId: $('input[name="categoryId"]', '#editMaterialForm').val(),
                                    isEnabled: $('input[name="isEnabled"]:checked', '#editMaterialForm').val(),
                                    safetyStock: $('input[name="safetyStock"]:checked', '#editMaterialForm').val()
                                });
                                
                                // 获取分类树数据来设置正确的分类名称
                                $.ajax({
                                    url: '/MaterialType/GetTreeAsyncgrx',
                                    type: 'GET',
                                    success: function(treeRes) {
                                        if(treeRes && treeRes.length > 0) {
                                            // 递归查找分类名称
                                            function findCategoryName(categories, targetId) {
                                                for(var i = 0; i < categories.length; i++) {
                                                    if(categories[i].id == targetId) {
                                                        return categories[i].title;
                                                    }
                                                    if(categories[i].children && categories[i].children.length > 0) {
                                                        var childResult = findCategoryName(categories[i].children, targetId);
                                                        if(childResult) return childResult;
                                                    }
                                                }
                                                return null;
                                            }
                                            
                                            var categoryName = findCategoryName(treeRes, detailData.materielTypeId);
                                            if(categoryName) {
                                                $('#editTreeSelectorInput').val(categoryName);
                                            } else {
                                                $('#editTreeSelectorInput').val('未知分类');
                                            }
                                        }
                                    }
                                });

                                // 如果有图片，显示图片
                                if(detailData.materielUrl) {
                                    $('#editUploadPreview').removeClass('layui-hide').find('img').attr('src', detailData.materielUrl);
                                    $('#editUploadImage i').hide();
                                } else {
                                    $('#editUploadPreview').addClass('layui-hide');
                                    $('#editUploadImage i').show();
                                }

                                // 初始化编辑表单的分类选择器
                                initEditCategorySelector();

                                // 重新渲染表单组件（延迟一点执行，确保DOM更新完成）
                                setTimeout(function() {
                                    form.render();
                                    
                                    // 再次验证表单值是否正确设置
                                    console.log('表单渲染后的值验证:', {
                                        materialCode: $('input[name="materialCode"]', '#editMaterialForm').val(),
                                        materialName: $('input[name="materialName"]', '#editMaterialForm').val(),
                                        unit: $('select[name="unit"]', '#editMaterialForm').val()
                                    });
                                }, 100);
                            }
                        });
                    } else {
                        layer.msg(res.msg || '获取详细数据失败');
                    }
                },
                error: function(){
                    layer.close(loading);
                    layer.msg('网络错误，获取数据失败');
                }
            });
        } else if(obj.event === 'del'){
            layer.confirm('您确定要删除这条记录吗？删除后将无法恢复！', {
                title: '删除确认',
                icon: 3, // 问号图标
                btn: ['确定删除', '取消'], // 按钮文字
                btn1: function(index) {
                    // 点击确定删除
                    var loading = layer.load(1, {
                        shade: [0.3, '#000'] // 加载遮罩
                    });
                    
                    $.ajax({
                        url: '/Materialproductmanagement/DeleteMaterial',
                        type: 'POST',
                        data: { id: data.id },
                        success: function(res){
                            layer.close(loading);
                            if(res.code === 0){
                                layer.close(index); // 关闭确认弹窗
                                obj.del(); // 从表格中移除行
                                layer.msg(res.msg || '删除成功', {
                                    icon: 1,
                                    time: 2000
                                });
                                table.reload('materialTable'); // 刷新表格
                            } else {
                                layer.msg(res.msg || '删除失败', {icon: 2});
                            }
                        },
                        error: function(xhr, status, error){
                            layer.close(loading);
                            var errorMsg = '删除失败';
                            if(xhr.responseText) {
                                try {
                                    var errorObj = JSON.parse(xhr.responseText);
                                    errorMsg = errorObj.msg || errorObj.message || '服务器错误';
                                } catch(e) {
                                    errorMsg = '服务器错误: ' + xhr.status;
                                }
                            }
                            layer.msg(errorMsg, {icon: 2});
                        }
                    });
                },
                btn2: function(index) {
                    // 点击取消
                    layer.close(index);
                }
            });
        }
    });

    // 修改按钮点击事件
    $('#editBtn').on('click', function(){
        var checkStatus = table.checkStatus('materialTable');
        if(checkStatus.data.length === 0){
            layer.msg('请选择要修改的记录');
            return;
        }
        if(checkStatus.data.length > 1){
            layer.msg('只能选择一条记录进行修改');
            return;
        }
        
        var data = checkStatus.data[0];
        
        // 调用后端API获取详细数据
        var loading = layer.load(1);
        $.ajax({
            url: '/Materialproductmanagement/GetMaterialproductById',
            type: 'GET',
            data: { id: data.id },
            success: function(res){
                layer.close(loading);
                if(res.code === 0){
                    var detailData = res.data;
                    
                    // 打开修改弹窗
                    layer.open({
                        type: 1,
                        title: '修改物料/产品',
                        area: ['800px', '90%'],
                        content: $('#editMaterialForm'),
                        success: function(){
                            // 设置隐藏的ID字段
                            window.editingMaterialId = detailData.id;
                            
                            // 直接设置表单字段值
                            $('input[name="materialCode"]', '#editMaterialForm').val(detailData.materielCode);
                            $('input[name="materialName"]', '#editMaterialForm').val(detailData.materielName);
                            $('input[name="specModel"]', '#editMaterialForm').val(detailData.specifications);
                            $('select[name="unit"]', '#editMaterialForm').val(detailData.unitsId);
                            
                            // 设置单选框
                            $('input[name="isEnabled"][value="' + (detailData.isNo === 1 ? 'true' : 'false') + '"]', '#editMaterialForm').prop('checked', true);
                            $('input[name="safetyStock"][value="' + (detailData.isSecure === 1 ? 'true' : 'false') + '"]', '#editMaterialForm').prop('checked', true);

                            // 设置物料分类ID
                            $('input[name="categoryId"]', '#editMaterialForm').val(detailData.materielTypeId);
                            
                            console.log('设置完成后的表单值验证:', {
                                materialCode: $('input[name="materialCode"]', '#editMaterialForm').val(),
                                materialName: $('input[name="materialName"]', '#editMaterialForm').val(),
                                specModel: $('input[name="specModel"]', '#editMaterialForm').val(),
                                unit: $('select[name="unit"]', '#editMaterialForm').val(),
                                categoryId: $('input[name="categoryId"]', '#editMaterialForm').val(),
                                isEnabled: $('input[name="isEnabled"]:checked', '#editMaterialForm').val(),
                                safetyStock: $('input[name="safetyStock"]:checked', '#editMaterialForm').val()
                            });
                            
                            // 获取分类树数据来设置正确的分类名称
                            $.ajax({
                                url: '/MaterialType/GetTreeAsyncgrx',
                                type: 'GET',
                                success: function(treeRes) {
                                    if(treeRes && treeRes.length > 0) {
                                        // 递归查找分类名称
                                        function findCategoryName(categories, targetId) {
                                            for(var i = 0; i < categories.length; i++) {
                                                if(categories[i].id == targetId) {
                                                    return categories[i].title;
                                                }
                                                if(categories[i].children && categories[i].children.length > 0) {
                                                    var childResult = findCategoryName(categories[i].children, targetId);
                                                    if(childResult) return childResult;
                                                }
                                            }
                                            return null;
                                        }
                                        
                                        var categoryName = findCategoryName(treeRes, detailData.materielTypeId);
                                        if(categoryName) {
                                            $('#editTreeSelectorInput').val(categoryName);
                                        } else {
                                            $('#editTreeSelectorInput').val('未知分类');
                                        }
                                    }
                                }
                            });

                            // 如果有图片，显示图片
                            if(detailData.materielUrl) {
                                $('#editUploadPreview').removeClass('layui-hide').find('img').attr('src', detailData.materielUrl);
                                $('#editUploadImage i').hide();
                            } else {
                                $('#editUploadPreview').addClass('layui-hide');
                                $('#editUploadImage i').show();
                            }

                            // 初始化编辑表单的分类选择器
                            initEditCategorySelector();

                            // 重新渲染表单组件（延迟一点执行，确保DOM更新完成）
                            setTimeout(function() {
                                form.render();
                                
                                // 再次验证表单值是否正确设置
                                console.log('表单渲染后的值验证:', {
                                    materialCode: $('input[name="materialCode"]', '#editMaterialForm').val(),
                                    materialName: $('input[name="materialName"]', '#editMaterialForm').val(),
                                    unit: $('select[name="unit"]', '#editMaterialForm').val()
                                });
                            }, 100);
                        }
                    });
                } else {
                    layer.msg(res.msg || '获取详细数据失败');
                }
            },
            error: function(){
                layer.close(loading);
                layer.msg('网络错误，获取数据失败');
            }
        });
    });

    // 批量删除按钮点击事件
    $('#deleteBtn').on('click', function(){
        var checkStatus = table.checkStatus('materialTable');
        if(checkStatus.data.length === 0){
            layer.msg('请选择要删除的记录');
            return;
        }
        
        var deleteCount = checkStatus.data.length;
        var confirmText = deleteCount === 1 ? 
            '您确定要删除这条记录吗？删除后将无法恢复！' : 
            `您确定要删除这${deleteCount}条记录吗？删除后将无法恢复！`;
            
        layer.confirm(confirmText, {
            title: '删除确认',
            icon: 3, // 问号图标
            btn: ['确定删除', '取消'], // 按钮文字
            btn1: function(index) {
                // 点击确定删除
                var loading = layer.load(1, {
                    shade: [0.3, '#000'] // 加载遮罩
                });
                
                var ids = checkStatus.data.map(function(item){ return item.id; });
                $.ajax({
                    url: '/Materialproductmanagement/BatchDeleteMaterial',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(ids),
                    success: function(res){
                        layer.close(loading);
                        if(res.code === 0){
                            layer.close(index); // 关闭确认弹窗
                            layer.msg(res.msg || '删除成功', {
                                icon: 1,
                                time: 2000
                            });
                            table.reload('materialTable'); // 刷新表格
                        } else {
                            layer.msg(res.msg || '删除失败', {icon: 2});
                        }
                    },
                    error: function(xhr, status, error){
                        layer.close(loading);
                        var errorMsg = '删除失败';
                        if(xhr.responseText) {
                            try {
                                var errorObj = JSON.parse(xhr.responseText);
                                errorMsg = errorObj.msg || errorObj.message || '服务器错误';
                            } catch(e) {
                                errorMsg = '服务器错误: ' + xhr.status;
                            }
                        }
                        layer.msg(errorMsg, {icon: 2});
                    }
                });
            },
            btn2: function(index) {
                // 点击取消
                layer.close(index);
            }
        });
    });

    // 初始化BOM表格
    var bomTable = table.render({
        elem: '#bomDetailTable',
        url: '/Materialproductmanagement/GetBomList',
        method: 'get',
        where: {
            materialId: ''  // 初始为空
        },
        page: {
            curr: 1,
            limit: 10
        },
        cols: [[
            {type: 'checkbox'},
            {field: 'materielCode', title: '物料编码', width: 120},
            {field: 'materielName', title: '物料名称', width: 150},
            {field: 'specifications', title: '规格', width: 120},
            {field: 'unitsId', title: '单位', width: 80},
            {field: 'useRatio', title: '使用比例', width: 100},
            {field: 'remark', title: '备注', width: 150},
            {title: '操作', width: 150, templet: function(d){
                return '<a class="layui-btn layui-btn-xs" lay-event="editBom">修改</a>' +
                       '<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="deleteBom">删除</a>';
            }}
        ]],
        limits: [10, 20, 50],
        limit: 10,
        text: {
            none: '暂无BOM数据'
        }
    });

    // BOM表格工具条事件
    table.on('tool(bomDetailTable)', function(obj){
        var data = obj.data;
        if(obj.event === 'editBom'){
            layer.open({
                type: 1,
                title: '修改BOM',
                area: ['500px', '400px'],
                content: '<div style="padding: 20px;">' +
                        '<form class="layui-form" lay-filter="bomEditForm">' +
                        '<div class="layui-form-item">' +
                        '<label class="layui-form-label">物料编码</label>' +
                        '<div class="layui-input-block">' +
                        '<input type="text" name="materielCode" value="'+ data.materielCode +'" readonly class="layui-input">' +
                        '</div>' +
                        '</div>' +
                        '<div class="layui-form-item">' +
                        '<label class="layui-form-label">使用比例</label>' +
                        '<div class="layui-input-block">' +
                        '<input type="number" name="useRatio" value="'+ data.useRatio +'" required lay-verify="required" class="layui-input">' +
                        '</div>' +
                        '</div>' +
                        '<div class="layui-form-item">' +
                        '<label class="layui-form-label">备注</label>' +
                        '<div class="layui-input-block">' +
                        '<textarea name="remark" class="layui-textarea">'+ (data.remark || '') +'</textarea>' +
                        '</div>' +
                        '</div>' +
                        '<div class="layui-form-item">' +
                        '<div class="layui-input-block">' +
                        '<button class="layui-btn" lay-submit lay-filter="bomEditSubmit">确定</button>' +
                        '<button type="button" class="layui-btn layui-btn-primary" onclick="layer.closeAll()">取消</button>' +
                        '</div>' +
                        '</div>' +
                        '</form>' +
                        '</div>',
                success: function(){
                    form.render();
                }
            });
        } else if(obj.event === 'deleteBom'){
            layer.confirm('确定删除此BOM记录？', function(index){
                $.ajax({
                    url: '/Materialproductmanagement/DeleteBom',
                    type: 'POST',
                    data: { id: data.id },
                    success: function(res){
                        if(res.code === 0){
                            layer.msg('删除成功');
                            obj.del();
                        } else {
                            layer.msg(res.msg || '删除失败');
                        }
                    }
                });
                layer.close(index);
            });
        }
    });

    // BOM编辑表单提交事件
    form.on('submit(bomEditSubmit)', function(data){
        var loading = layer.load();
        $.ajax({
            url: '/Materialproductmanagement/UpdateBom',
            type: 'POST',
            data: data.field,
            success: function(res){
                layer.close(loading);
                if(res.code === 0){
                    layer.closeAll('page');
                    layer.msg('修改成功');
                    bomTable.reload();
                } else {
                    layer.msg(res.msg || '修改失败');
                }
            },
            error: function(){
                layer.close(loading);
                layer.msg('服务器错误');
            }
        });
        return false;
    });

    // 编辑表单中的新增BOM按钮点击事件
    $(document).on('click', '#editAddBomBtn', function(){
        // 打开物料选择弹窗
        layer.open({
            type: 1,
            title: '选择物料',
            area: ['1400px', '800px'],
            content: $('#bomMaterialSelectDialog'),
            success: function(){
                // 加载树形结构数据
                $.ajax({
                    url: '/MaterialType/GetTreeAsyncgrx',
                    type: 'GET',
                    success: function(res) {
                        if(res && res.length > 0) {
                            // 渲染树形结构
                            tree.render({
                                elem: '#bomMaterialTree',
                                data: [{
                                    title: '物料分类',
                                    id: 0,
                                    spread: true,
                                    children: res
                                }],
                                click: function(obj){
                                    if(obj.data.id > 0) {
                                        // 点击树节点时刷新表格数据
                                        table.reload('bomMaterialTable', {
                                            where: {
                                                categoryId: obj.data.id
                                            },
                                            page: { curr: 1 }
                                        });
                                    }
                                }
                            });
                        }
                    }
                });

                // 初始化物料选择表格
                table.render({
                    elem: '#bomMaterialTable',
                    url: '/Materialproductmanagement/GetMaterialproductModel',
                    method: 'get',
                    where: {
                        code: '',
                        name: ''
                    },
                    request: {
                        pageName: 'page',
                        limitName: 'limit'
                    },
                    parseData: function(res) {
                        return {
                            "code": res.code || 0,
                            "msg": res.msg || '',
                            "count": res.pageCount || 0,
                            "data": res.listDate || []
                        };
                    },
                    cols: [[
                        {type: 'radio', width: 50},
                        {field: 'materielCode', title: '物料编码', width: 150},
                        {field: 'materielName', title: '物料名称', width: 200},
                        {field: 'materielUrl', title: '物料图片', width: 120, templet: function(d){
                            return d.materielUrl ? '<img src="'+ d.materielUrl +'" alt="物料图片" style="max-height:30px;">' : '';
                        }},
                        {field: 'specifications', title: '规格型号', width: 150},
                        {field: 'unitsId', title: '单位', width: 100},
                        {field: 'materielTypeId', title: '所属分类', width: 120},
                        {field: 'isNo', title: '是否启用', width: 100, templet: function(d){
                            return d.isNo === 1 ? '<span class="layui-badge layui-bg-green">是</span>' : '<span class="layui-badge layui-bg-gray">否</span>';
                        }},
                        {field: 'isSecure', title: '安全库存', width: 100, templet: function(d){
                            return d.isSecure === 1 ? '<span class="layui-badge layui-bg-green">是</span>' : '<span class="layui-badge layui-bg-gray">否</span>';
                        }},
                        {field: 'createTime', title: '创建时间', width: 180}
                    ]],
                    page: true,
                    limit: 10,
                    limits: [10, 20, 30, 40, 50]
                });

                // 搜索按钮点击事件
                $('#bomSearchBtn').off('click').on('click', function(){
                    var code = $('input[name="materialCode"]', '#bomMaterialSelectDialog').val();
                    var name = $('input[name="materialName"]', '#bomMaterialSelectDialog').val();
                    
                    table.reload('bomMaterialTable', {
                        where: {
                            code: code,
                            name: name
                        },
                        page: { curr: 1 }
                    });
                });

                // 确定按钮点击事件
                $('#confirmBomSelectBtn').off('click').on('click', function(){
                    var checkStatus = table.checkStatus('bomMaterialTable');
                    if(checkStatus.data.length === 0){
                        layer.msg('请选择物料');
                        return;
                    }

                    var selectedData = checkStatus.data[0];
                    
                    // 构造新的BOM行数据
                    var newBomRow = {
                        materielCode: selectedData.materielCode,
                        materielName: selectedData.materielName,
                        specifications: selectedData.specifications,
                        unitsId: selectedData.unitsId,
                        useRatio: 1, // 默认使用比例为1
                        remark: ''
                    };

                    // 添加新行到BOM表格
                    var newRow = '<tr>' +
                        '<td><input type="checkbox" lay-skin="primary"></td>' +
                        '<td>' + newBomRow.materielCode + '</td>' +
                        '<td>' + newBomRow.materielName + '</td>' +
                        '<td>' + (newBomRow.specifications || '') + '</td>' +
                        '<td>' + newBomRow.unitsId + '</td>' +
                        '<td>' + newBomRow.useRatio + '</td>' +
                        '<td>' + (newBomRow.remark || '') + '</td>' +
                        '<td>' +
                        '<a class="layui-btn layui-btn-xs layui-btn-primary" lay-event="editBom">修改</a>' +
                        '<a class="layui-btn layui-btn-xs layui-btn-primary" lay-event="deleteBom">删除</a>' +
                        '</td>' +
                        '</tr>';

                    // 将新行添加到BOM表格中
                    $('#bomTableBody').append(newRow);
                    
                    // 更新总条数
                    var currentCount = $('#bomTableBody tr').length;
                    $('#bomTotalCount').text('共 ' + currentCount + ' 条');

                    // 重新渲染表单元素
                    form.render();

                    // 获取当前弹窗的索引并关闭物料选择弹窗
                    var selectDialogIndex = layer.index;
                    layer.close(selectDialogIndex);
                    
                    layer.msg('添加成功');
                });
            }
        });
    });

    // 编辑按钮点击事件（表格行内的编辑按钮）
    $(document).on('click', '[lay-event="editBom"]', function(){
        var $tr = $(this).closest('tr');
        var materielCode = $tr.find('td:eq(1)').text();
        var materielName = $tr.find('td:eq(2)').text();
        var specifications = $tr.find('td:eq(3)').text();
        var unitsId = $tr.find('td:eq(4)').text();
        var useRatio = $tr.find('td:eq(5)').text();
        var remark = $tr.find('td:eq(6)').text();

        layer.open({
            type: 1,
            title: '修改产品BOM关系',
            area: ['600px', '500px'],
            content: '<div class="layui-form" style="padding: 20px;">' +
                    '<div class="layui-form-item">' +
                    '<label class="layui-form-label">BOM物料编码</label>' +
                    '<div class="layui-input-block">' +
                    '<input type="text" name="materielCode" value="' + materielCode + '" readonly class="layui-input">' +
                    '</div>' +
                    '</div>' +
                    '<div class="layui-form-item">' +
                    '<label class="layui-form-label">BOM物料名称</label>' +
                    '<div class="layui-input-block">' +
                    '<input type="text" name="materielName" value="' + materielName + '" readonly class="layui-input">' +
                    '</div>' +
                    '</div>' +
                    '<div class="layui-form-item">' +
                    '<label class="layui-form-label">BOM物料规格</label>' +
                    '<div class="layui-input-block">' +
                    '<textarea name="specifications" readonly class="layui-textarea">' + specifications + '</textarea>' +
                    '</div>' +
                    '</div>' +
                    '<div class="layui-form-item">' +
                    '<label class="layui-form-label">BOM物料单位</label>' +
                    '<div class="layui-input-block">' +
                    '<input type="text" name="unitsId" value="' + unitsId + '" readonly class="layui-input">' +
                    '</div>' +
                    '</div>' +
                    '<div class="layui-form-item">' +
                    '<label class="layui-form-label"><span style="color: red;">*</span> 物料使用比例</label>' +
                    '<div class="layui-input-block">' +
                    '<div class="layui-input-group">' +
                    '<button type="button" class="layui-btn layui-btn-primary" id="decreaseRatio">-</button>' +
                    '<input type="number" name="useRatio" value="' + useRatio + '" required lay-verify="required" class="layui-input" style="text-align: center;" step="0.0001" min="0">' +
                    '<button type="button" class="layui-btn layui-btn-primary" id="increaseRatio">+</button>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '<div class="layui-form-item">' +
                    '<label class="layui-form-label">备注</label>' +
                    '<div class="layui-input-block">' +
                    '<textarea name="remark" class="layui-textarea" placeholder="请输入备注">' + remark + '</textarea>' +
                    '</div>' +
                    '</div>' +
                    '<div class="layui-form-item" style="text-align: center;">' +
                    '<button class="layui-btn" lay-submit lay-filter="editBomSubmit">确定</button>' +
                    '<button type="button" class="layui-btn layui-btn-primary" onclick="layer.close(layer.index)">取消</button>' +
                    '</div>' +
                    '</div>',
            success: function(layero, index){
                form.render();
                
                // 增加/减少比例按钮事件
                $('#increaseRatio').on('click', function(){
                    var $input = $('input[name="useRatio"]');
                    var currentVal = parseFloat($input.val()) || 0;
                    $input.val((currentVal + 0.0001).toFixed(4));
                });
                
                $('#decreaseRatio').on('click', function(){
                    var $input = $('input[name="useRatio"]');
                    var currentVal = parseFloat($input.val()) || 0;
                    if(currentVal > 0) {
                        $input.val(Math.max(0, currentVal - 0.0001).toFixed(4));
                    }
                });
                
                // 监听编辑表单提交
                form.on('submit(editBomSubmit)', function(data){
                    // 更新表格中的数据
                    $tr.find('td:eq(5)').text(data.field.useRatio);
                    $tr.find('td:eq(6)').text(data.field.remark);
                    
                    // 只关闭当前编辑弹窗，保留主编辑弹窗
                    layer.close(index);
                    layer.msg('修改成功');
                    return false;
                });
            }
        });
    });

    // 删除按钮点击事件（表格行内的删除按钮）
    $(document).on('click', '[lay-event="deleteBom"]', function(){
        var $tr = $(this).closest('tr');
        layer.confirm('确定删除此BOM记录？', function(index){
            $tr.remove();
            // 更新总条数
            var currentCount = $('#bomTableBody tr').length;
            $('#bomTotalCount').text('共 ' + currentCount + ' 条');
            layer.close(index);
            layer.msg('删除成功');
        });
    });

    // 全选/取消全选
    form.on('checkbox(bomCheckAll)', function(data){
        var $checkboxes = $('#bomTableBody input[type="checkbox"]');
        $checkboxes.prop('checked', data.elem.checked);
        form.render('checkbox');
    });

    // 编辑表单中的批量删除BOM按钮点击事件
    $(document).on('click', '#editDeleteBomBtn', function(){
        var $checkedRows = $('#bomTableBody input[type="checkbox"]:checked').closest('tr');
        if($checkedRows.length === 0){
            layer.msg('请选择要删除的记录');
            return;
        }
        
        layer.confirm('确定删除选中的记录？', function(index){
            $checkedRows.remove();
            // 更新总条数
            var currentCount = $('#bomTableBody tr').length;
            $('#bomTotalCount').text('共 ' + currentCount + ' 条');
            layer.close(index);
            layer.msg('删除成功');
        });
    });

    // 页面加载完成后自动加载数据
    loadCategoryData();
});
</script>
</body>
</html>

